package com.dhecp.project.storage.controller;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.DateUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.service.ModuleNidAndBidService;
import com.dhecp.project.storage.domain.HwFinalPaymentSon;
import com.dhecp.project.storage.domain.HwFinalstatement;
import com.dhecp.project.storage.domain.HwFinalstatementSelect;
import com.dhecp.project.storage.domain.HwFinalstatementdetail;
import com.dhecp.project.storage.mapper.HwFinalPaymentSonMapper;
import com.dhecp.project.storage.service.HwFinalstatementService;
import com.dhecp.project.storage.service.HwFinalstatementdetailService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.dhecp.project.common.controller.BaseModuleController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 尾程对账单(HwFinalstatement)控制层
 *
 * @author fxz
 * @since 2023-09-11 15:14:20
 */
@Controller
@RequestMapping("/storage/hwFinalstatement")
public class HwFinalstatementController extends BaseModuleController{

    private String prefix = "storage/hwFinalstatement";
    private String moduleTable = ModuleTable.HW_FINALSTATEMENT;
    private String moduleTable1 = ModuleTable.HW_FINALSTATEMENTDETAIL;

    @Autowired
    private HwFinalstatementService hwFinalstatementService;

    @Autowired
    private ModuleNidAndBidService moduleNidAndBidService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private HwFinalstatementdetailService hwFinalstatementdetailService;

    @Autowired
    private HwFinalPaymentSonMapper hwFinalPaymentSonMapper;


    /**
     * @Description: 打开查询列表页
     * @Param: [params]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-08-15 15:42
     */
    @RequiresPermissions("storage:hwFinalstatement:view")
    @GetMapping()
    public ModelAndView view(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new HwFinalstatement()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/hwFinalstatement"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");

        ModelAndView mv = this.openListPage(params);
        mv.addObject("storage", "hwFinalstatement");
        return mv;
    }

    /**
     * @Description: 查询页 列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: hlf
     * @date: 2022-08-15 15:43
     */
    @RequiresPermissions("storage:hwFinalstatement:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        List<HwFinalstatement> list = new ArrayList<HwFinalstatement>();
        try {
            list = hwFinalstatementService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 打开制单页
     * @Param: nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-08-15 15:42
     */
    @RequiresPermissions("storage:hwFinalstatement:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put("moduleTable", moduleTable);
        params.put("entity", new HwFinalstatement()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        params.put("moduleUrl", prefix); //页面上级路径
        params.put("prefix", prefix + "/hwFinalstatement_edit"); //页面路径
        Subject userSubject = ShiroUtils.getSubject();
        int enableEdit = 0;
        boolean vType = false;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())) {
            if (userSubject.isPermitted("storage:hwFinalstatement:edit")) { //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }

        try {
            Map<String, Object> headData = new HashMap<String, Object>();        //表头的业务数据
            HwFinalstatement businessData = hwFinalstatementService.queryFirstRecord(params);
            if (businessData == null) { //未查询到对应单据，页面初始化值
                ModuleNidAndBid moduleNidAndBid = moduleNidAndBidService.queryModuleNidAndBidInitial(params);
                HwFinalstatement hwFinalstatement = new HwFinalstatement();
                hwFinalstatement.setNid("0");
                hwFinalstatement.setBid(moduleNidAndBid.getBid());
                hwFinalstatement.setCode(moduleNidAndBid.getBid());
                hwFinalstatement.setCreateTime(new Date());
                hwFinalstatement.setCid(ShiroUtils.getMandatorCid());
                hwFinalstatement.setCidName(ShiroUtils.getMandatorCidName());
                hwFinalstatement.setbUser(ShiroUtils.getMandatorId());
                hwFinalstatement.setbUserName(ShiroUtils.getMandatorName());
                hwFinalstatement.setbDept(ShiroUtils.getMandatorDeptPath());
                hwFinalstatement.setbPosition(ShiroUtils.getMandatorPositionNameDa());
                hwFinalstatement.setaUser(ShiroUtils.getUserId());
                hwFinalstatement.setaUserName(ShiroUtils.getUserName());
                hwFinalstatement.setaDept(ShiroUtils.getUserDeptPath());
                hwFinalstatement.setaDeptName(ShiroUtils.getUserDeptName());
                hwFinalstatement.setaPosition(ShiroUtils.getUserPositionNameDa());
                headData = TypeUtils.entityToMap(hwFinalstatement);
            } else {
                headData = TypeUtils.entityToMap(businessData);
                vType = businessData.getEffectStock();
            }
            params.put("headData", headData); //表头的业务数据

            params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
            ModelAndView mv = this.openEditPage(params);
            mv.addObject("nowTimeStr", DateUtils.getDate());    //当前日期
            mv.addObject("enableEdit", vType ? 0 : enableEdit); //当前页面是否可编辑（0：不可编辑，1：可编辑）
            if (businessData != null) {
                Map<String, Object> params2 = new HashMap<String, Object>();
                params2.put("moduleTable", moduleTable1);
                params2.put("tpCode", businessData.getBid());
                mv.addObject("List", hwFinalstatementdetailService.queryList(params2));//母件数据
            }
            //取商品子件列表网格
            params.put("moduleTable", moduleTable1);
            params.put("entity", new HwFinalstatementdetail()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("readOnly", vType);//生成列是否可编辑
            params.put("toolBarWidth", 0);//操作区
            params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段
            mv.addObject("importFields", dictionaryForFieldService.queryFieldFrontImport(params));	//导入模板字段
            mv.addObject("gridColumnsZJ", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));

            return mv;
        } catch (Exception e) {
            return this.gotoModelAndViewErrorPage(e.getMessage());    //详细信息
        }

    }

    /**
     * 打开对账单选择页面
     *
     * @param params
     * @return ModelAndView
     * @author fxz
     */
    @GetMapping("/select2")
    public ModelAndView selectbusinessList(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new HwFinalstatement()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);
        if (params.get("pagetype") != null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))
            params.put("checkBox", "yes");
        else params.put("radio", "yes");
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("prefix", "storage/hwFinalstatement");
        mv.addObject("moduleTable", moduleTable);
        mv.addObject("fmoduleTable", moduleTable);
        mv.addObject("pagetype", params.get("pagetype").toString());
        if (params.get("selectedObject") != null && params.get("selectedObject") != "") {
            String selectedObject = params.get("selectedObject").toString();
            mv.addObject("selectedObject", selectedObject);
        }
        mv.setViewName("system/organization/mzjobject_select");
        return mv;
    }

    /**
     * @Description: 下载模版
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: fxz
     * @date: 2023-08-24 15:43
     */
    @RequiresPermissions("storage:hwTailprogram:export")
    @Log(title = "对账单导出", businessType = BusinessType.EXPORT)
    @GetMapping("/template")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult template(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable1);
        params.put("entity", new HwFinalstatementdetail());

        params.put("getFieldAttributesType", "template");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<HwFinalstatementdetail> util = new ExportExcelUtils<HwFinalstatementdetail>(moduleTable1, new HwFinalstatementdetail());
        return util.exportExcel(null, fieldList, "尾程对账单", "template");
    }

    /**
     * @Description: 数据导出Excel
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: fxz
     * @date: 2022-08-15 15:43
     */
    @RequiresPermissions("storage:hwTailprogram:export")
    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new HwFinalstatement());

        List<HwFinalstatement> list = hwFinalstatementService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<HwFinalstatement> util = new ExportExcelUtils<HwFinalstatement>(moduleTable, new HwFinalstatement());
        return util.exportExcel(list, fieldList, "尾程对账单", "export");
    }

    /**
     * @Description: 保存数据
     * @Param: infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: fxz
     * @date: 2023-09-12 15:44
     */
    @RequiresPermissions(value = {"storage:hwTailprogram:add", "storage:hwTailprogram:edit", "storage:hwTailprogram:delete"}, logical = Logical.OR)
    @Log(title = "对账单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editpost(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = hwFinalstatementService.saveData(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: hlf
     *@date: 2022-05-09 11:40
     */
    @RequiresPermissions("storage:hwTailprogram:view")
    @GetMapping("/lastnid")
    @ResponseBody
    public AjaxResult lastNid(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = hwFinalstatementService.queryLastNid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: hlf
     *@date: 2022-05-09 11:40
     */
    @RequiresPermissions("storage:hwTailprogram:view")
    @GetMapping("/nextnid")
    @ResponseBody
    public AjaxResult nextNid(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = hwFinalstatementService.queryNextNid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * 打开流转页
     * @param fType 必要参数：审核类型（flow_go：流转，flow_back：退回）
     * @param infoMap 必要参数：非网格字段（包括所有显示和隐藏的字段），json格式字符串
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("storage:hwFinalstatement:flow")
    @PostMapping("/flowpage")
    @ResponseBody
    public AjaxResult flowPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("prefix", prefix);
        return openFlowPage(params);
    }

    /**
     *@Description: 流转
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:42
     */
    @RequiresPermissions("storage:hwFinalstatement:flow")
    @Log(title = "尾程对账流转", businessType = BusinessType.FLOWGO)
    @PostMapping("/flowgopost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult flowGoSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= hwFinalstatementService.updateFlowGo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 退回
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:42
     */
    @RequiresPermissions("storage:hwFinalstatement:flow")
    @Log(title = "尾程对账", businessType = BusinessType.FLOWBACK)
    @PostMapping("/flowbackpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult flowBackSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= hwFinalstatementService.updateFlowBack(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }



    /**
     * @Description: 查询页 列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: fxz
     * @date: 2023-06-08
     */
    @RequiresPermissions("storage:hwFinalstatement:list")
    @GetMapping("/hwFinalStatementList")
    @ResponseBody
    public TableDataInfo hwFinalStatementList(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable1);
        List<HwFinalstatementSelect> list = new ArrayList<HwFinalstatementSelect>();
        List<HwFinalPaymentSon> hwFinalPaymentSonList = hwFinalPaymentSonMapper.queryListCode(params.get("bid").toString());
        StringBuffer sb = new StringBuffer();
        for (HwFinalPaymentSon hwFinalPaymentSon : hwFinalPaymentSonList){
            sb.append(hwFinalPaymentSon.getFsBid()).append(",");
        }
        String codereconcile = " (t1.stateName = '已对账')";
        if (sb.length() != 0){
            String sb1 = sb.toString().substring(0,sb.length()-1);
            codereconcile = "t1.tpCode in ('" + sb1.replace(",", "','") + "')";
        }
        params.put("codereconcile", codereconcile);

        try {
            list = hwFinalstatementService.queryListSelect(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     *@Description: 查询已选择的商品
     *@Param: selectedUser ：已选中的商品编号字符串，示例：0000,1001,1002
     *@return: com.dhecp.common.core.page.TableDataInfo
     *@Author: hlf
     *@date: 2022-08-18 17:13
     */
    @GetMapping("/listselect")
    @ResponseBody
    public TableDataInfo userInfoSelectListJson(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable1);
        List<HwFinalstatementSelect> list = new ArrayList<HwFinalstatementSelect>();
        if (params.get("selectedUser") != null && params.get("selectedUser") != ""){
            String wherestrhand = "t1.bid in ('" + params.get("selectedUser").toString().replace(",", "','") + "')";
            params.put("wherestrhand", wherestrhand);
            try{
                list = hwFinalstatementService.queryListSelect(params);
            }catch(Exception e){
                return getDataTable(this.getExceptionMessage(e).toString());
            }
        }else{
            return getDataTable("请传入已选中的商品编码字符串（selectedUser），取值示例：0000,1001,1002");
        }
        return getDataTable(list);
    }
}

